import { defineStore } from "pinia";

/**
 * @zh_CN 访问权限相关
 */
export const useAccessStore = defineStore("core-access", {
  state: () => ({
    accessCodes: [], // 权限码
    accessMenus: [], // 可访问的菜单列表
    accessRoutes: [], // 可访问的路由列表
    accessToken: null, // 登录 accessToken
    isAccessChecked: false, // 是否已经检查过权限

    loginExpired: false, // 登录是否过期
    refreshToken: null //登录 accessToken
  }),
  actions: {
    getMenuByPath(path) {
      function findMenu(menus, path) {
        for (const menu of menus) {
          if (menu.path === path) {
            return menu;
          }
          if (menu.children) {
            const matched = findMenu(menu.children, path);
            if (matched) {
              return matched;
            }
          }
        }
      }
      return findMenu(this.accessMenus, path);
    },

    setAccessCodes(codes) {
      this.accessCodes = codes;
    },
    setAccessMenus(menus) {
      this.accessMenus = menus;
    },
    setAccessRoutes(routes) {
      this.accessRoutes = routes;
    },
    setAccessToken(token) {
      this.accessToken = token;
    },
    setIsAccessChecked(isAccessChecked) {
      this.isAccessChecked = isAccessChecked;
    },
    setLoginExpired(loginExpired) {
      this.loginExpired = loginExpired;
    },
    setRefreshToken(token) {
      this.refreshToken = token;
    }
  }
});
